package com.xutianpeng.disk.user.control;

import com.alibaba.fastjson.JSON;
import com.xutianpeng.disk.mybatis.entity.PtUserEntity;
import com.xutianpeng.disk.mybatis.flexigrid.PagingEntity;
import com.xutianpeng.disk.mybatis.flexigrid.TblResponseEntity;
import com.xutianpeng.disk.mybatis.ztree.ZtreeEntity;
import com.xutianpeng.disk.spring.control.BaseController;
import com.xutianpeng.disk.user.entity.SearchUserEntity;
import com.xutianpeng.disk.user.exeption.EmailRepeatException;
import com.xutianpeng.disk.user.exeption.MobileRepeatException;
import com.xutianpeng.disk.user.exeption.UserNameRepeatException;
import com.xutianpeng.disk.user.exeption.UserOccupyException;
import com.xutianpeng.disk.user.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private final Log logger = LogFactory.getLog(this.getClass());
    @Resource
    private UserService userService;

    @RequestMapping("/queryUserList")
    @ResponseBody
    public List<PtUserEntity> queryUserList() {
        List<PtUserEntity> list = userService.queryUserList();
        return list;
    }


    @RequestMapping("/deleteUserByIds")
    @ResponseBody
    public String deleteUserByIds(@RequestParam("ids") String ids)  {

        try {
            userService.deleteUserByIds(ids);
        } catch (UserOccupyException e) {
//            e.printStackTrace();
            return failJson("user.delete.fail",e.getMessage());
        }
        return successJson("user.delete.success");
    }

    @RequestMapping("/userPage")
    public String userPage(){
        return "user/userPage";
    }
    @RequestMapping("/queryUserInfoListByPage")
    @ResponseBody
    public  TblResponseEntity <PtUserEntity>  queryUserInfoListByPage(SearchUserEntity entity ,PagingEntity paging){
        TblResponseEntity <PtUserEntity> responseEntity = userService.queryUserInfoListByPage(entity,paging);
        return  responseEntity;
    }

    @RequestMapping("/queryUserInfoById")
    @ResponseBody
    public  String  queryUserInfoById(@RequestParam("userUuid") String userUuid){
        PtUserEntity entity = userService.queryUserInfoById(userUuid);
        return JSON.toJSONString(entity);
    }

    @RequestMapping("/modifyUserInfoById")
    @ResponseBody
    public  String  modifyUserInfoById(PtUserEntity entity){
        try {
            userService.modifyUserInfoById(entity);
        } catch (EmailRepeatException e) {
            return failJson("user.email.repeat");
//            e.printStackTrace();
        } catch (MobileRepeatException e) {
            return failJson("user.mobile.repeat");
//            e.printStackTrace();
        } catch (UserNameRepeatException e) {
            return failJson("user.name.repeat");
//            e.printStackTrace();
        }
        return successJson("user.modify.success");
    }

    @RequestMapping("/addUserInfo")
    @ResponseBody
    public  String  addUserInfo(PtUserEntity entity){
        try {
            userService.addUserInfo(entity);
        } catch (EmailRepeatException e) {
            return failJson("user.email.repeat");
//            e.printStackTrace();
        } catch (MobileRepeatException e) {
            return failJson("user.mobile.repeat");
//            e.printStackTrace();
        } catch (UserNameRepeatException e) {
            return failJson("user.name.repeat");
//            e.printStackTrace();
        }
        return successJson("user.add.success");
    }

    @RequestMapping("/queryRoleTreeListByUser")
    @ResponseBody
    public String queryRoleTreeListByUser(@Param("userUuid") String userUuid){
        List<ZtreeEntity> list = userService.queryRoleTreeListByUser(userUuid);
        return JSON.toJSONString(list);
    }
    @RequestMapping("/saveRoleRefUser")
    @ResponseBody
    public String saveRoleRefUser(@Param("userUuidArray") String userUuidArray, @Param("roleUuidArray") String roleUuidArray){
        userService.saveRoleRefUser(userUuidArray,roleUuidArray);
        return successJson("user.allocat.role.success");
    }

    @RequestMapping("/getCurrentUserInfo")
    @ResponseBody
    public String getCurrentUserInfo() {
        try {
            // 从Spring Security上下文获取当前登录用户的认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || authentication.getName() == null) {
                // 未登录或登录信息失效（返回错误提示，使用BaseController的failJson方法）
                return failJson("user.not.login", "请先登录");
            }

            // 获取当前登录用户名（假设登录标识为用户名，与PtUserEntity的userName一致）
            String currentUsername = authentication.getName();

            // 调用服务层查询用户详情（需在UserService中实现该方法）
            PtUserEntity currentUser = userService.getUserByUsername(currentUsername);
            if (currentUser == null) {
                return failJson("user.not.exists", "当前用户信息不存在");
            }

            // 返回用户信息JSON（前端用于填充修改表单）
            return JSON.toJSONString(currentUser);
        } catch (Exception e) {
            logger.error("接口执行失败", e);
            return failJson("user.query.error", "获取用户信息失败：" + e.getMessage());
        }
    }
    /**
     * 重置用户密码（单个或批量）
     */
    @RequestMapping("/resetPassword")
    @ResponseBody
    public String resetPassword(@RequestParam("userUuids") String userUuids) {
        try {
            if (!StringUtils.hasText(userUuids)) {
                return failJson("请选择需要重置密码的用户");
            }

            String[] uuids = userUuids.split(",");
            userService.resetPassword(uuids);
            return successJson("user.reset.pwd.success");
        } catch (Exception e) {
            logger.error("重置密码失败", e);
            return failJson("user.reset.pwd.fail", e.getMessage());
        }
    }

    /**
     * 用户设置新密码
     */
    @RequestMapping("/setNewPassword")
    @ResponseBody
    public String setNewPassword(
            @RequestParam("userUuid") String userUuid,
            @RequestParam("newPassword") String newPassword) {
        try {
            userService.setNewPassword(userUuid, newPassword);
            return successJson("user.set.pwd.success");
        } catch (IllegalArgumentException e) {
            return failJson(e.getMessage());
        } catch (Exception e) {
            logger.error("设置新密码失败", e);
            return failJson("user.set.pwd.fail", e.getMessage());
        }
    }
}